<?php

namespace App\Library\Util;

class ToolUtil
{
    use Singleton;

    public function numberToExcelColumn($num)
    {
        $column = '';
        while ($num > 0) {
            $num--; // 因为我们要从 A 开始，所以需要减去 1
            $remainder = $num % 26;
            $char = chr(65 + $remainder); // 65 是 ASCII 码中的 'A'
            $column = $char . $column; // 将字符添加到左侧
            $num = (int)($num / 26);
        }
        return $column;
    }

    public function getExcelColumn($num)
    {
        $columnArr = [];
        for ($i = 1; $i <= $num; $i++) {
            $columnArr[] = $this->numberToExcelColumn($i);
        }
        return $columnArr;
    }

    function getColumnIndex($columnName)
    {
        $columnName = strtoupper($columnName); // 确保列名是大写的
        $index = 0;
        $length = strlen($columnName);

        for ($i = 0; $i < $length; $i++) {
            $index *= 26;
            $index += ord($columnName[$i]) - ord('A') + 1;
        }

        return $index - 1; // 因为数组下标是从0开始的，所以需要减1
    }

    public function getIpRegion($ip)
    {
        try {
            $ipDb = new \Ip2Region();
            $ipAddress = $ipDb->memorySearch($ip)['region'] ?? '';
        } catch (\Exception $e) {
            $ipAddress = $ip;
        }
        return $ipAddress;
    }
}
